﻿using CGT.API.API;
using CGT.API.Common;
using CGT.API.Models;
using CGT.API.Models.WxMini;
using Newtonsoft.Json.Linq;
using OF.Component.BLL;
using OF.Component.Enum;
using OF.Component.Model;
using OF.Utility;
using OF.Utility.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace CGT.API.Controllers
{
    /// <summary>
    /// 微信小程序相关
    /// </summary>
    public class WxMiniController : BaseApiController
    {
        /// <summary>
        /// 微信小程序appid
        /// </summary>
        string AppId = ConfigHelper.GetValue("WxMini.AppId");

        /// <summary>
        /// 微信小程序AppSecret
        /// </summary>
        string AppSecret = ConfigHelper.GetValue("WxMini.AppSecret");

        /// <summary>
        /// 根据用户授权码获取用户ID
        /// </summary>
        /// <param name="model"></param>
        /// <returns>用户ID</returns>
        [HttpPost]
        public ResultData<MiniUserModel> AddUserInfoByAuthorizationCode(MiniRegisterModel model)
        {
            ResultData<MiniUserModel> rData = new ResultData<MiniUserModel>();
            MiniUserModel miniModel = new MiniUserModel();
            //获取微信openid
            var rt = GetSession(model.AuthorizationCode);
            if (rt.status == 0)
            {
                miniModel.ThirdUserID = rt.data.openid;
                miniModel.Sessionkey = rt.data.session_key;
            }
            else
            {
                rData.status = rt.status;
                rData.message = rt.message;
                return rData;
            }

            //查询用户是否注册 
            var userSource = UserSourceOperate.GetByToken(miniModel.ThirdUserID, (int)ThirdUserSourceEnum.WxMini);
            if (userSource != null)
            {
                miniModel.UserID = userSource.UserID;

                //获取用户信息
                var usrInfo = UserOperate.GetByID(miniModel.UserID);
                if (usrInfo != null)
                {
                    miniModel.AuthLevel = usrInfo.UserLevel;
                    miniModel.UserMobile = usrInfo.UserMobile;
                    miniModel.ThirdUserName = usrInfo.UserName;
                    miniModel.ThirdUserHead = usrInfo.HeadImg;
                }
            }
            else
            {
                UserSourceOperate.Insert(new UserSourceInfo()
                {
                    SourceToken = miniModel.ThirdUserID,
                    SourceType = (int)ThirdUserSourceEnum.WxMini,
                    SourceUserHead = model.ThirdUserHead,
                    SourceUserName = model.ThirdUserName,
                    CreatedDate=DateTime.Now                    
                });
                miniModel.UserID = 0;
                miniModel.AuthLevel = 0;
            }

            rData.data = miniModel;
            return rData;
        }

        /// <summary>
        /// 添加用户(微信授权获取手机号码)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultData<UserMobileModel> AddUser(GetPhoneNumberModel model)
        {
            //返回值格式:{"phoneNumber":"18201032670","purePhoneNumber":"18201032670","countryCode":"86","watermark":{"timestamp":1545018096,"appid":"wxb3947f8af58393c9"}}
            string result = SecurityUtility.DecodeEncryptedData(model.Sessionkey, model.encryptedData, model.iv);

            JObject jobj = JObject.Parse(result);
            JToken token = jobj.GetValue("phoneNumber");
            if (token == null)
            {
                return ResultData<UserMobileModel>.Error("获取电话号码失败.");
            }
            else
            {
                var oExistedUser = UserOperate.GetUserByMobile(token.Value<string>());
                if (oExistedUser == null)
                {
                    oExistedUser = new UserInfo();
                    oExistedUser.CreatedDate = DateTime.Now;
                    oExistedUser.UpdatedDate = DateTime.Now;
                    oExistedUser.IsActive = 1;
                    oExistedUser.UserType = 1;
                    oExistedUser.UserLevel = 0;
                    oExistedUser.UserMobile = token.Value<string>();
                    oExistedUser.UserID = UserOperate.Insert(oExistedUser);
                }

                //更新第三方来源信息
                if (!string.IsNullOrEmpty(model.ThirdUserID))
                {
                    var userSourceInfo = UserSourceOperate.GetByToken(model.ThirdUserID, model.ThirdUserSource);
                    if (userSourceInfo != null)
                    {
                        userSourceInfo.UserID = oExistedUser.UserID;
                        UserSourceOperate.Update(userSourceInfo);
                    }
                }
                //UserCenterClient usrClient = new UserCenterClient();
                //ResultDataOfResponseUserAdd userAdd = usrClient.User_AddOrGetAsync(new RequestUserAdd()
                //{
                //    UserType = 1,
                //    UserLevel = 0,
                //    SourceToken = model.ThirdUserID,
                //    SourceType = model.ThirdUserSource,
                //    UserMobile = token.Value<string>()
                //}).Result;

                return ResultData<UserMobileModel>.Success(new UserMobileModel()
                {
                    UserID = oExistedUser.UserID,
                    UserMobile = token.Value<string>()
                });
            }
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userID"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<MiniUserModel> GetUseInfo(int userID)
        {
            ResultData<MiniUserModel> rData = new ResultData<MiniUserModel>();
            MiniUserModel miniModel = new MiniUserModel();
            //获取用户信息
            var usrInfo = UserOperate.GetByID(userID);
            if (usrInfo != null)
            {
                miniModel.AuthLevel = usrInfo.UserLevel;
                miniModel.UserMobile = usrInfo.UserMobile;
                miniModel.ThirdUserName = usrInfo.UserName;
                miniModel.ThirdUserHead = usrInfo.HeadImg;
                miniModel.UserID = userID;
            }

            var usrSource = UserSourceOperate.GetByID(userID);
            if (usrSource != null)
            {
                miniModel.ThirdUserID = usrSource.SourceToken;
            }

            rData.data = miniModel;
            return rData;
        }


        /// <summary>
        /// 更新用户头像
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultData<int> UpdateUserHead(MiniUserModel model)
        {
            //UserCenterClient usrClient = new UserCenterClient();
            //ResultDataOfInt32 result = usrClient.UserSource_UpdateHeadAsync(new ReqUserHeadUpdate()
            //{
            //    SourceUserHead = model.ThirdUserHead,
            //    SourceUserName = model.ThirdUserName,
            //    SourceToken = model.ThirdUserID,
            //    SourceType = (int)ThirdUserSourceEnum.WxMini
            //}).Result;
            int result = UserSourceOperate.UpdateUserHead(model.ThirdUserHead, model.ThirdUserName, model.ThirdUserID, (int)ThirdUserSourceEnum.WxMini);
            UserSourceInfo userSourceInfo = UserSourceOperate.GetByToken(model.ThirdUserID, (int)ThirdUserSourceEnum.WxMini);
            if (userSourceInfo != null && userSourceInfo.UserID > 0)
            {
                //更新用户偶像
                UserOperate.UpdateUserHead(userSourceInfo.UserID, userSourceInfo.SourceUserName, userSourceInfo.SourceUserHead);
            }
            return ResultData<int>.Success(result);
            //if (result.Status == 0)
            //{
            //    return ResultData<int>.Success(result.Data.Value);
            //}
            //return ResultData<int>.Error(result.Message);
        }

        /// <summary>
        /// 发送模板消息
        /// </summary>
        /// <param name="model">参数</param>
        /// <returns></returns>
        [HttpPost]
        public ResultData<string> SendTemplateMessage(TemplateMessageModel model)
        {
            ResultData<string> rData = new ResultData<string>();
            string url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={0}";
            //消息内容
            var data = new
            {
                keyword1 = new TemplateDataItem("2017451265"),
                keyword2 = new TemplateDataItem("100元")
            };

            TemplateModel tempModel = new TemplateModel()
            {
                data = data,
                form_id = model.FormId,
                template_id = "A7GsNXBFf90bPNhu_85YSf38itU8OCWud1y6vB2CpcA",
                touser = model.OpenId
            };

            AccessTokenResult accessToken = GetAccessToken();
            if (!string.IsNullOrEmpty(accessToken.access_token))
            {
                string strResult = HttpWebRequestService.GetRequest(string.Format(url, accessToken.access_token), Newtonsoft.Json.JsonConvert.SerializeObject(tempModel), "POST", "", null);
                rData.data = strResult;

                TemplateResult result = Newtonsoft.Json.JsonConvert.DeserializeObject<TemplateResult>(strResult);
                rData.status = result.errcode;
                if (result.errcode != 0)
                {
                    Log4netLog.Debug(strResult);
                }
            }

            return rData;
        }

        /// <summary>
        /// 获取会话token
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public AccessTokenResult GetAccessToken()
        {
            AccessTokenResult result = new AccessTokenResult();
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}", AppId, AppSecret);
            string strResult = HttpWebRequestService.GetRequest(url, "", "GET", "text/html", null);
            if (strResult.Contains("errcode") || strResult.Contains("errmsg"))
            {
                Log4netLog.Debug(strResult);
            }
            else
            {
                result = Newtonsoft.Json.JsonConvert.DeserializeObject<AccessTokenResult>(strResult);
            }
            return result;
        }

        /// <summary>
        /// 获取微信小程序授权码
        /// </summary>
        /// <param name="authCode">授权码</param>
        /// <returns></returns>
        public ResultData<JsCode2Session> GetSession(string authCode)
        {
            try
            {
                string url = string.Format("https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code", AppId, AppSecret, authCode);
                string result = HttpWebRequestService.GetRequest(url, "", "POST", "application/json; charset=UTF-8", null);
                Log4netLog.Debug(result);
                JObject jobj = JObject.Parse(result);
                JToken token = jobj.GetValue("openid");
                if (token == null)
                {
                    Log4netLog.Debug("微信小程序授权码：" + authCode);
                    Log4netLog.Debug(result);

                    return ResultData<JsCode2Session>.Error(result);
                }
                else
                {
                    JsCode2Session data = new JsCode2Session();
                    data.openid = token.Value<string>();
                    data.session_key = jobj.GetValue("session_key").Value<string>();
                    return ResultData<JsCode2Session>.Success(data);
                }
            }
            catch (Exception ex)
            {
                Log4netLog.Error(ex);
            }
            return ResultData<JsCode2Session>.Success();
        }
    }
}
